/*
 * Copyright (C) 2011 Francesco Feltrinelli <first_name DOT last_name AT gmail DOT com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#ifndef BUFFEREDPACKETUNMARSHALLER_H_
#define BUFFEREDPACKETUNMARSHALLER_H_

#include "PacketMarshaller.h"
#include "Unmarshaller.h"
#include "../Common/Consts.h"
#include "../Server/CharVector.h"

class BufferedPacketUnmarshaller : public Unmarshaller {
public:
	BufferedPacketUnmarshaller();
	virtual ~BufferedPacketUnmarshaller() { };

	template <int N> // defined here because of the template
	std::vector<PktPtr> unmarshal(CharArray<N> & bytes, std::size_t length){
		// Append bytes to buffer
		buffer.insert(buffer.end(), bytes.begin(), bytes.begin()+length);
		return unmarshalAll();
	}

private:
	// Initial space reserved for buffer
	static const std::size_t BUFFER_START_LENGTH= 2048;


	CharVector buffer;

	PingPkt* decodePingPkt(char *bytes);
	UnSubPkt* decodeUnSubPkt(char *bytes);

	PktType decodePktType(char byte);
	std::size_t decodePktLength(char* bytes);

	PktPtr* unmarshalOne(CharVector & bytes);
	std::vector<PktPtr> unmarshalAll();
};


#endif /* BUFFEREDPACKETUNMARSHALLER_H_ */
